package com.shitou.shitouproduct.service.impl;

import com.shitou.shitoucommons.exception.RRException;
import com.shitou.shitoucommons.utils.AllSaltEnum;
import com.shitou.shitoucommons.utils.RespBean;
import com.shitou.shitouproduct.config.RabbitMQConfit;
import com.shitou.shitouproduct.entity.CategoryBrandRelationEntity;
import com.shitou.shitouproduct.entity.SpuInfoEntity;
import com.shitou.shitouproduct.service.CategoryBrandRelationService;
import com.shitou.shitouproduct.service.SpuInfoService;
import com.shitou.shitouproduct.vo.ProductInfoVo;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shitou.shitoucommons.utils.PageUtils;
import com.shitou.shitoucommons.utils.Query;

import com.shitou.shitouproduct.dao.BrandDao;
import com.shitou.shitouproduct.entity.BrandEntity;
import com.shitou.shitouproduct.service.BrandService;

import javax.annotation.Resource;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Resource
    private SpuInfoService spuInfoService;

    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource(name = "RedisTemplate")
    private RedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                new QueryWrapper<BrandEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * 通过分类id获得所有的品牌
     * @param categoryId
     * @return
     */
    @Override
    public RespBean getBrandByCategoryId(int categoryId) {

        List<CategoryBrandRelationEntity> listDo = categoryBrandRelationService.list(
                new QueryWrapper<CategoryBrandRelationEntity>().eq("category_id", categoryId)
                        .eq("status", 1));

        if ( listDo.size() <= 0 ){
            return RespBean.error("该分类暂时没有品牌方入驻");
        }

        List<BrandEntity> brandEntityList = listDo.stream().map( categoryBrandRelationEntity -> {
            BrandEntity brandDo = this.getOne(new QueryWrapper<BrandEntity>()
                    .eq("brand_id", categoryBrandRelationEntity.getBrandId())
                    .eq("status", 1)
                    .eq("show_status", 1));
            return brandDo;
        }).collect(Collectors.toList()).stream().filter(Objects::nonNull).collect(Collectors.toList());

        return RespBean.success().put("data", brandEntityList);
    }


    /**
     * 更新品牌显示状态
     * @param brand
     * @return
     */
    @Override
    public RespBean updateStatus(BrandEntity brand) {
        BrandEntity brand_id = this.getOne(new QueryWrapper<BrandEntity>().eq("brand_id", brand.getBrandId()));
        brand_id.setStatus(brand.getShowStatus());
        brand_id.setShowStatus(brand.getShowStatus());
        this.updateById(brand_id);

        // 如果该品牌不用了，那么,,将该品牌的商品全部下架
        updateProduct(brand.getBrandId(), brand.getShowStatus());
        return RespBean.success();
    }


    /**
     * 更新商品，因为品牌的启用或者弃用而导致该品牌下的商品全部上架或者下架
     * @param brandId
     * @param status
     */
    public void updateProduct(Long brandId, Integer status){
        // 获取品牌对应的商品--
        List<SpuInfoEntity> list = spuInfoService.list(new QueryWrapper<SpuInfoEntity>()
                .eq("brand_id", brandId).eq("status", 1));

        // 从redis中再次筛选可售卖商品
        String productToken = null;
        Iterator<SpuInfoEntity> iterator = list.iterator();
        while (iterator.hasNext()) {
            SpuInfoEntity next = iterator.next();
            Long id = next.getId();
            productToken = String.valueOf(new Sha256Hash(id.toString(), AllSaltEnum.SALT.getSalt()));
            Integer saleCount = (Integer) redisTemplate.opsForValue().get("saleCount:" + productToken);
            if ( saleCount == null || saleCount.equals(1) ){
                iterator.remove();
            }
        }

        spuInfoService.updateBatchById(list.stream().map(spuInfoEntity -> {
            // 上架状态设置为 status
            spuInfoEntity.setPublishStatus(status);
            // elasticSearch设置为不启用/或者启用
            rabbitTemplate.convertAndSend(
                    status==0?RabbitMQConfit.PRODUCT_SELL_QUEUE:RabbitMQConfit.PRODUCT_RELEASE_QUEUE,
                    spuInfoEntity.getId());
            return spuInfoEntity;
        }).collect(Collectors.toList()));
    }
}
